package com.retail.core.task;

import com.retail.core.entity.ParamReq;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.system.entity.request.CronTriggersRequest;
import com.retail.system.entity.vo.CronTriggersVo;
import com.retail.system.service.CronTriggersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class JobTaskCommandLineRunner implements CommandLineRunner {

    @Autowired
    private QuartzTaskBean quartzTaskBean;

    @Autowired
    private CronTriggersService cronTriggersService;

    @Autowired
    private Environment env;

    @Override
    public void run(String... args) throws Exception {
        String applicationName = env.getProperty("spring.application.name");
        if (TaskUtil.getRunApps().contains(applicationName)) {
            init();
        }
    }

    private void init() {
        // 初始化所有的已经启用的订阅
        List<CronTriggersVo> crons = findCrons();
        log.info("需要初始化的任务个数:{}", crons.size());
        for (CronTriggersVo cron : crons) {
            try {
                log.info("开始初始化订阅任务,任务name:{}", cron.getId());
                quartzTaskBean.createScheduleJob(cron);
            } catch (Exception e) {
                log.error("启动时初始化订阅任务失败:{}", e.getMessage());
            }
        }
    }

    private List<CronTriggersVo> findCrons() {
        ParamReq<CronTriggersRequest> paramReq = new ParamReq<CronTriggersRequest>();
        CronTriggersRequest request = new CronTriggersRequest();
        request.setDelFlag(DelFlagEnum.NO.getValue());
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        paramReq.setEntity(request);
        Integer total = cronTriggersService.countPage(paramReq);
        paramReq.setSize(total);
        return cronTriggersService.listPage(paramReq);
    }
}
